package hang.xipujewelWeb.web.account;

import hang.xipujewelWeb.dto.Dto;
import hang.xipujewelWeb.entity.account.User;
import hang.xipujewelWeb.entity.app.ExchangeRate;
import hang.xipujewelWeb.entity.app.Jewel;
import hang.xipujewelWeb.entity.app.ShoppingCart;
import hang.xipujewelWeb.service.account.ExchangeRateManager;
import hang.xipujewelWeb.service.account.JewelManager;
import hang.xipujewelWeb.service.account.PriceBaseNumberManager;
import hang.xipujewelWeb.service.account.ShoppingCartManager;
import hang.xipujewelWeb.service.account.UserManager;
import hang.xipujewelWeb.utils.SearchDtoUtil;
import hang.xipujewelWeb.utils.UserUtil;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;

import net.esoar.modules.web.BaseController;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/jewel")
public class JewelController extends BaseController<Jewel> {

	@Autowired
	private UserManager userManager;

	@Autowired
	private JewelManager jewelManager;

	@Autowired
	private PriceBaseNumberManager priceBaseNumberManager;

	@Autowired
	private ShoppingCartManager shoppingCartManager;

	@Autowired
	private ExchangeRateManager exchangeRateManager;

	@RequestMapping("")
	public String list(Model model, ServletRequest request) {
		Map<String, Object> searchParams = getFilters(request);
		String page = (String) searchParams.get("page");
		int pageNum;
		if (page == null || "".equals(page)) {
			pageNum = 0;
		} else {
			pageNum = Integer.parseInt(page);
		}
		Dto dto = SearchDtoUtil.intitDto(searchParams);
		dto.setPage(pageNum);

		User cUser = userManager.findUserByLoginName(UserUtil.getCurrentUserLoginName());
		List<Jewel> jewels = jewelManager.list(dto.getShape(), dto.getColor(), dto.getNeatness(), dto.getCut(),
				dto.getBuffing(), dto.getSymmetry(), dto.getFluorescence(), dto.getCard(), dto.getSite(),
				dto.getStartWeight(), dto.getEndWeight(), dto.getStartPrice(), dto.getEndPrice(), dto.getTop(),
				pageNum, cUser, dto.getOrder(), dto.getNum(), dto.getCardId(), dto.getHoldType());

		ExchangeRate exchangeRate = exchangeRateManager.getAll().get(0);
		for (Jewel jewel : jewels) {//重量X国际报价X折扣X汇率
			float discount = (float) ((100.0 + jewel.getDiscount() + cUser.getParent().getPriceBaseNumber()
					.getJewelBaseNumBer()) / 100.0);
			float priceRMB = jewel.getWeight() * jewel.getInternationalPrice() * (discount) * exchangeRate.getRate();
			jewel.setSecondPrice(priceRMB);//把算好的价格放在非持久化的字段中，传到前端显示
			jewel.setSecondDiscount((discount - 1) * 100);
		}

		/*long startTime = System.currentTimeMillis(); //获取开始时间
		int jewelNum = jewelManager.list(dto.getShape(), dto.getColor(), dto.getNeatness(), dto.getCut(),
				dto.getBuffing(), dto.getSymmetry(), dto.getFluorescence(), dto.getCard(), dto.getSite(),
				dto.getStartWeight(), dto.getEndWeight(), dto.getStartPrice(), dto.getEndPrice(), dto.getTop(), -1,
				cUser, dto.getOrder(), dto.getNum(), dto.getCardId(), dto.getHoldType()).size();
		long endTime = System.currentTimeMillis(); //获取结束时间

		System.out.println(formatLongToTimeStr(endTime - startTime));
		model.addAttribute("jewelNum", jewelNum);*/
		model.addAttribute("page", pageNum);
		model.addAttribute("cUser", cUser);
		model.addAttribute("jewels", jewels);
		model.addAttribute("rate", exchangeRate.getRate());

		return "jewel/jewel-list";
	}

	@RequestMapping("search")
	public String search(Model model, ServletRequest request, @RequestParam("isLoadMore") String isLoadMore,
			@RequestParam("page") String page) {
		Map<String, Object> searchParams = getFilters(request);
		int pageNum;
		if (page == null || "".equals(page)) {
			pageNum = 0;
		} else {
			pageNum = Integer.parseInt(page);
		}
		Dto dto = SearchDtoUtil.intitDto(searchParams);
		dto.setPage(pageNum);

		User cUser = userManager.findUserByLoginName(UserUtil.getCurrentUserLoginName());
		List<Jewel> jewels = jewelManager.list(dto.getShape(), dto.getColor(), dto.getNeatness(), dto.getCut(),
				dto.getBuffing(), dto.getSymmetry(), dto.getFluorescence(), dto.getCard(), dto.getSite(),
				dto.getStartWeight(), dto.getEndWeight(), dto.getStartPrice(), dto.getEndPrice(), dto.getTop(),
				pageNum, cUser, dto.getOrder(), dto.getNum(), dto.getCardId(), dto.getHoldType());

		ExchangeRate exchangeRate = exchangeRateManager.getAll().get(0);
		for (Jewel jewel : jewels) {//重量X国际报价X折扣X汇率
			float discount = (float) ((100.0 + jewel.getDiscount() + cUser.getParent().getPriceBaseNumber()
					.getJewelBaseNumBer()) / 100.0);
			float priceRMB = jewel.getWeight() * jewel.getInternationalPrice() * (discount) * exchangeRate.getRate();
			jewel.setSecondPrice(priceRMB);//把算好的价格放在非持久化的字段中，传到前端显示
			jewel.setSecondDiscount((discount - 1) * 100);
		}

		/*	int jewelNum = jewelManager.list(dto.getShape(), dto.getColor(), dto.getNeatness(), dto.getCut(),
					dto.getBuffing(), dto.getSymmetry(), dto.getFluorescence(), dto.getCard(), dto.getSite(),
					dto.getStartWeight(), dto.getEndWeight(), dto.getStartPrice(), dto.getEndPrice(), dto.getTop(), -1,
					cUser, dto.getOrder(), dto.getNum(), dto.getCardId(), dto.getHoldType()).size();

			model.addAttribute("jewelNum", jewelNum);*/
		model.addAttribute("page", pageNum);
		model.addAttribute("cUser", cUser);
		model.addAttribute("jewels", jewels);
		model.addAttribute("rate", exchangeRate.getRate());
		if ("1".equals(isLoadMore.trim())) {
			return "jewel/jewel-more-list";
		}
		return "jewel/jewel-search-list";
	}

	@RequestMapping("addShopCar")
	public String addShopCar(@RequestParam("id") long id) {
		Jewel jewel = jewelManager.get(id);
		ShoppingCart shoppingCart = new ShoppingCart();
		User user = userManager.findUserByLoginName(UserUtil.getCurrentUserLoginName());
		ShoppingCart shoppingCart2 = shoppingCartManager.findByUesrAndJewel(user.getId(), jewel.getId());

		if (shoppingCart2 == null) {
			shoppingCart.setJewel(jewel);
			shoppingCart.setUesr(user);
			shoppingCart.setAddTime(new Date());
			shoppingCartManager.save(shoppingCart);
		}

		return "redirect:/order/toCommit";
	}

	@RequestMapping("addShopCars")
	@ResponseBody
	public String addShopCars(@RequestParam("ids") List<Long> ids) {
		String message = "";
		User user = userManager.findUserByLoginName(UserUtil.getCurrentUserLoginName());
		for (Long id : ids) {
			Jewel jewel = jewelManager.get(id);
			ShoppingCart shoppingCart2 = shoppingCartManager.findByUesrAndJewel(user.getId(), jewel.getId());
			if (shoppingCart2 != null) {
				message = message + jewel.getNum() + ",";
			} else {
				ShoppingCart shoppingCart = new ShoppingCart();
				shoppingCart.setJewel(jewel);
				shoppingCart.setUesr(user);
				shoppingCart.setAddTime(new Date());
				shoppingCartManager.save(shoppingCart);
			}
		}
		if (!"".equals(message)) {
			return message + "已经存在购物车中，其他钻石加入购物车成功";
		}
		return "加入购物车成功";
	}

	@Override
	public String baseMapping() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String getModelName() {
		// TODO Auto-generated method stub
		return null;
	}

	public static String formatLongToTimeStr(Long l) {
		String str = "";
		int hour = 0;
		int minute = 0;
		int second = 0;
		second = l.intValue() / 1000;
		if (second > 60) {
			minute = second / 60;
			second = second % 60;
		}

		if (minute > 60) {
			hour = minute / 60;
			minute = minute % 60;
		}
		String strtime = hour + "小时" + minute + "分钟" + second + "秒";
		return strtime;

	}

}
